package com.SinaMicrobloggingAPI.Core.Request;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.SinaMicrobloggingAPI.Core.OauthConstants;
import com.SinaMicrobloggingAPI.Core.Response.IResponse;
import com.SinaMicrobloggingAPI.Util.ChangeCharset;
import com.SinaMicrobloggingAPI.Util.HttpUtility;
import com.SinaMicrobloggingAPI.Util.StringBuilder2;

/**
 * @author Administrator
 * 
 */
public class StatusesUpdateRequest extends RequestBase {

	private static final String STATUES_UPDATE = "StatusesUpdate";
	private static final String STATUS = "status";
	private String status = "";

	public StatusesUpdateRequest(IResponse response, String userId,
			String password, String status) {
		super(response);
		// TODO Auto-generated constructor stub
		this.status = handingString(status);
		this.password = password;
		this.userId = userId;
	}

	@Override
	protected String getRequestName() {
		// TODO Auto-generated method stub
		return STATUES_UPDATE;
	}

	protected HttpMethodEnum getHttpMethod() {
		return HttpMethodEnum.POST;
	}

	protected String getRequestParamenters() {

		BasicNameValuePair oauth_token = new BasicNameValuePair(
				OauthConstants.OAUTH_TOKEN_KEY, getOauthToken());
		BasicNameValuePair oauth_status = new BasicNameValuePair(STATUS, status);
		BasicNameValuePair oauth_source = new BasicNameValuePair("source",
				super.getConsumerKey());
		oauthParamenterModels.add(oauth_token);
		oauthParamenterModels.add(oauth_status);
		oauthParamenterModels.add(oauth_source);
		return super.getRequestParamenters();
	}

	public IResponse getResponse() {

		String requestUrl = getRequestUrlWithNoParamenters();
		String parameneters = getRequestParamenters();
		String signatureString = generateSignatureString(requestUrl,
				parameneters);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(requestUrl);
		try {
			parameneters = String.format("%s&%s=%s", parameneters,
					OauthConstants.OAUTH_SIGNATURE_KEY, signatureString);
			HttpEntity postentity = new ByteArrayEntity(parameneters
					.getBytes(HTTP.UTF_8));
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httpPost.getParams().setBooleanParameter(
					CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
			httpPost.getParams().setParameter(
					CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
			httpPost.getParams().setParameter(
					CoreProtocolPNames.HTTP_ELEMENT_CHARSET, HTTP.UTF_8);
			httpPost.setEntity(postentity);
			HttpResponse httpResponse = httpclient.execute(httpPost);
			HttpEntity responseentity = httpResponse.getEntity();
			if (responseentity != null) {
				String result = EntityUtils.toString(responseentity);
				response.ParseResult(result.replaceAll("\r", ""));
				System.out.println(result);
				httpclient.getConnectionManager().shutdown();
			}
		} catch (Exception ex) {
			httpPost.abort();
			throw new RuntimeException(ex);
		}

		return response;
	}

	public IResponse getResponse2() {

		String requestUrl = getRequestUrlWithNoParamenters();
		String parameneters = getRequestParamenters();
		String signatureString = generateSignatureString(requestUrl,
				parameneters);
		parameneters = String.format("%s&%s=%s", parameneters,
				OauthConstants.OAUTH_SIGNATURE_KEY, signatureString);
		URL url = null;
		try {
			url = new URL(requestUrl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		connection.setDoInput(true);
		connection.setDoOutput(true);
		try {
			connection.setRequestMethod("POST");
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		try {
			connection.connect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DataOutputStream outputStream = null;
		try {
			outputStream = new DataOutputStream(connection.getOutputStream());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			outputStream.writeBytes(parameneters);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			outputStream.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			outputStream.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		InputStream inputStream = null;
		try {
			inputStream = connection.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = -1;
		try {
			while ((len = inputStream.read(b)) != -1) {
				arrayOutputStream.write(b, 0, len);
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String content = arrayOutputStream.toString();
		try {
			arrayOutputStream.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			arrayOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connection.disconnect();

		System.out.println("content:" + content);

		return null;
	}

}
